<template>
  <div class="generator-container">
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <h2>生成表情包</h2>
        </div>
      </template>

      <el-form :model="formData" label-position="top">
        <!-- 文本输入 -->
        <el-form-item label="输入文本">
          <el-input 
            v-model="formData.text" 
            placeholder="请输入要生成的表情包文字"
            type="textarea"
            :rows="3"
          />
        </el-form-item>

        <!-- 风格选择 -->
        <el-form-item label="选择风格">
          <el-select v-model="formData.style" placeholder="请选择风格">
            <el-option label="卡通风格" value="cartoon" />
            <el-option label="写实风格" value="realistic" />
            <el-option label="艺术风格" value="artistic" />
            <el-option label="动漫风格" value="anime" />
            <el-option label="漫画风格" value="comic" />
          </el-select>
        </el-form-item>

        <!-- 生成按钮 -->
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading"
            @click="handleGenerate"
            :disabled="!formData.text"
          >
            生成表情包
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 生成结果 -->
      <div v-if="generatedUrl" class="result-container">
        <h3>生成结果</h3>
        <img :src="generatedUrl" class="result-image" />
        <el-button type="success" @click="handleDownload">下载表情包</el-button>
      </div>
    </el-card>

    <!-- 最近生成 -->
    <div class="recent-history">
      <h3>最近生成</h3>
      <div class="history-list">
        <div v-for="item in recentHistory" :key="item.history_id" class="history-item">
          <img :src="item.output_url" :alt="item.text">
          <div class="item-info">
            <p>{{ item.text }}</p>
            <p>{{ item.created_at }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'
import { useRouter } from 'vue-router'
import axios from 'axios'

const generatedUrl = ref('')
const loading = ref(false)
const router = useRouter()
const recentHistory = ref([])

const formData = reactive({
  text: '',
  style: 'cartoon',
  is_dynamic: false
})

// 生成表情包
const handleGenerate = async () => {
  if (!formData.text) {
    ElMessage.warning('请输入要生成的文字')
    return
  }
  
  const token = localStorage.getItem('token')
  console.log('Token before request:', token)
  
  if (!token) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  
  loading.value = true
  try {
    const requestData = {
      text: formData.text,
      style: formData.style
    }

    // 使用 fetch 发送请求
    const response = await fetch('http://localhost:5000/api/generate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(requestData)
    })

    // 打印完整的请求信息
    console.log('Request details:', {
      url: 'http://localhost:5000/api/generate',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: requestData
    })

    const data = await response.json()
    console.log('Response:', data)

    if (!response.ok) {
      throw new Error(data.message || '请求失败')
    }

    if (data.status === 'success') {
      generatedUrl.value = `http://localhost:5000${data.data.image_url}`
      ElMessage.success('生成成功')
    } else {
      ElMessage.error(data.message || '生成失败')
    }
  } catch (error) {
    console.error('Generate error:', error)
    if (error.message.includes('401')) {
      ElMessage.error('请重新登录')
      router.push('/login')
    } else {
      ElMessage.error(error.message || '生成失败')
    }
  } finally {
    loading.value = false
  }
}

// 下载生成的表情包
const handleDownload = () => {
  if (!generatedUrl.value) return
  
  const link = document.createElement('a')
  link.href = generatedUrl.value
  link.download = `emoji-${Date.now()}.png`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const loadRecentHistory = async () => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      console.log('No user ID found')
      return
    }

    const response = await request.get(`/history/${userId}`)
    console.log('Recent history response:', response)
    
    if (response.data.status === 'success') {
      recentHistory.value = response.data.data.records
    }
  } catch (error) {
    console.error('Failed to load recent history:', error)
  }
}

onMounted(() => {
  loadRecentHistory()
})
</script>

<style scoped>
.generator-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.upload-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-container {
  margin-top: 20px;
  text-align: center;
}

.result-image {
  max-width: 100%;
  margin: 20px 0;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-button {
  margin-top: 10px;
}

.recent-history {
  margin-top: 20px;
}

.history-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 10px;
}

.history-item {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
}

.history-item img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.item-info {
  padding: 10px;
}

.item-info p {
  margin: 5px 0;
}
</style> 